#include<string>
using namespace std;
class Solution {
public:
    int nextGreaterElement(int n) {
        string str = to_string(n);
        for (int i = str.size() - 2; i >= 0; --i) {
            if (str[i] < str[i + 1]) {
                int j = i + 1;
                while (j < str.size()) {
                    if (str[i] >= str[j])
                        break;
                    ++j;
                }
                swap(str[i], str[j - 1]);
                reverse(str.begin() + i + 1, str.end());
                long long val = 0;
                for (int k = 0; k < str.size(); ++k)
                    val = 10 * val + str[k]-'0';
                if (val > INT_MAX)
                    return -1;
                else
                    return val;
            }
        }
        return -1;

    }
};

//int main() {
//    Solution sol;
//    sol.nextGreaterElement(12);
//}